//
//  NSRongYunManager.m
//  Meboo
//
//  Created by kyo on 2024/5/21.
//

#import "NSRongYunManager.h"
#import <RongCloudOpenSource/RongIMKit.h>
@implementation NSRongYunManager
+ (NSRongYunManager *)sharedManager {
    static dispatch_once_t onceToken;
    static NSRongYunManager *obj;
    dispatch_once(&onceToken, ^{
        obj = [[self alloc] init];
    });
    return obj;
}

- (void)getRongCloudToken {
    __WeakSelf
    [[MBChatDataManager sharedManager] getRongCloudToken:^(BOOL success) {
        if (success) {
            [weakSelf getRongCloudConnectState];
        }
    }];
}

- (void)getRongCloudConnectState {
    __WeakSelf
    [[RCIM sharedRCIM] connectWithToken:[MBUserAccount defaultAccount].rongCloudToken
                               dbOpened:^(RCDBErrorCode code) {
        //消息数据库打开，可以进入到主页面
    } success:^(NSString *userId) {
        //连接成功,可跳转至会话列表页
        //存储本人的userid
        MBUserAccount  *account = [MBUserAccount defaultAccount];
        account.chatUserId = userId;
        [MBUserAccount  saveAccount:account];
        
        if ([MBUserAccount defaultAccount].kefuTargetId.length > 0) {
            [weakSelf setUnReadMessage];
        } else {
            [[MBChatDataManager sharedManager] getChatKefuUrl:^(RCUserInfo * _Nonnull userInfo) {
                if (userInfo) {
                    [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:userInfo.userId];
                    MBUserAccount  *account = [MBUserAccount defaultAccount];
                    account.kefuTargetId = userInfo.userId;
                    [MBUserAccount saveAccount:account];
                    [weakSelf setUnReadMessage];
                }
            }];
        }
    }error:^(RCConnectErrorCode status) {
        if (status == RC_CONN_TOKEN_INCORRECT) {
            //从 APP 服务获取新 token，并重连
            NSLog(@"");
        } else {
            //无法连接到 IM 服务器，请根据相应的错误码作出对应处理
            NSLog(@"");
        }
    }];
}

- (void)setUnReadMessage {
    MBUserAccount  *account = [MBUserAccount defaultAccount];
    [[RCCoreClient sharedCoreClient] getTotalUnreadCountWith:^(int unreadCount) {
        [[RCCoreClient sharedCoreClient] getUnreadCount:ConversationType_PRIVATE targetId:[MBUserAccount defaultAccount].kefuTargetId completion:^(int count) {
            dispatch_async(dispatch_get_main_queue(), ^{
                account.unReadNum = unreadCount-count;
                [MBUserAccount  saveAccount:account];
                // 非主线程，将UI操作切换到主线程进行
                [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_MESSAGE_UNREAD object:nil];
            });
        }];
    }];
}
@end
